﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Senparc.Weixin.MP.CommonAPIs;
using System.Web.Security;
namespace Lion.WeiXin.Controllers
{

    public class OrderController : Controller
    {
        IOrder iorder = new OrderDAO();
        IVipCard ivip = new VipCardDAO();

        DBContext db;

        public OrderController()
            : this(null)
        {

        }

        public OrderController(DBContext mockDB)
        {
            if (mockDB == null)
            {
                db = new DBContext();
            }
            else
            {
                db = mockDB;
            }
        }

        [PermissionFilter]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string orderCode, string cardID, string payType, string createDate, int currentPage, int pageSize)
        {
            //如果传入条件参数
            orderCode = HttpUtility.UrlDecode(orderCode);
            payType = HttpUtility.UrlDecode(payType);
            //订单数据采用数据库分页
            string where = " 1=1 ";
            if (!string.IsNullOrEmpty(orderCode))
            {
                where += string.Format(" and Code ='{0}' ", orderCode);
            }
            if (!string.IsNullOrEmpty(cardID))
            {
                where += string.Format(" and Buyer ='{0}' ", cardID);
            }
            if (!string.IsNullOrEmpty(payType))
            {
                where += string.Format(" and PayType ='{0}' ", payType);
            }
            if (!string.IsNullOrEmpty(createDate))
            {
                DateTime dt = DateTime.Parse(createDate);
                where += string.Format(" and CreateDate >= '{0}' and CreateDate< '{1}' ", dt.ToString("yyyy-MM-dd HH:mm:ss"), dt.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
            }
            List<OrderModel> list = db.Orders.GetList(pageSize, currentPage, where);
            int totalCount = db.Orders.GetRecordCount(where);

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        [PermissionFilter]
        [LogFilter("修改订单", OperateLogTypeEnum.订单日志, "Id")]
        public ActionResult Show(string action, string Id)
        {
            OrderModel model = db.Orders.GetModel(Id);
            //查询购买人信息
            VipCardModel vipCard = db.VipCards.GetModel(model.Buyer);
            ViewData["card"] = vipCard;
            return View(model);
        }

        public ActionResult Details(string Id)
        {
            OrderModel model = db.Orders.GetModel(Id);
            //查询购买人信息
            VipCardModel vipCard = db.VipCards.GetModel(model.Buyer);
            ViewData["card"] = vipCard;
            return View(model);
        }

        [PermissionFilter]
        [LogFilter("确认消费", OperateLogTypeEnum.订单日志, "orderCode")]
        /// <summary>
        /// 确认消费
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult ConfirmPayed(string orderCode)
        {
            OrderModel model = db.Orders.GetModel(orderCode);
            if (!string.IsNullOrEmpty(model.Code))
            {
                model.Status = (int)OrderStateEnum.结单;
                model.LastUpdateDate = DateTime.Now;
                model.Creator = CurrentUser.UserName;
                iorder.PayBill(model);
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "更改成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "订单不存在!" });
            }
        }

        [LogFilter("作废订单", OperateLogTypeEnum.订单日志, "orderID")]
        /// <summary>
        /// 作废订单
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public JsonResult BecomeInValid(string orderID)
        {
            OrderModel model = db.Orders.GetModel(orderID);
            if (!string.IsNullOrEmpty(model.Code))
            {
                model.Status = (int)OrderStateEnum.废单;
                model.LastUpdateDate = DateTime.Now;
                model.Creator = CurrentUser.UserName;
                iorder.PayBill(model);
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "更改成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "订单不存在!" });
            }
        }

        [LogFilter("修改订单备注", OperateLogTypeEnum.订单日志, "id,remark")]
        public JsonResult EditRemark(string id, string remark)
        {
            OrderModel model = db.Orders.GetModel(id);
            if (model != null)
            {
                model.LastUpdateDate = DateTime.Now;
                model.Creator = CurrentUser.UserName;
                model.Buyer_Note = remark;
                iorder.Update(model);
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "更改成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "订单不存在!" });
            }
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.Orders.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

        [LogFilter("创建订单", OperateLogTypeEnum.订单日志)]
        public ActionResult Create()
        {
            InitProductType(0);
            OrderModel items = new OrderModel();
            return View(items);
        }

        private void InitProductType(int selectID)
        {
            //加载产品类型
            List<DictionaryModel> dic_pro_types = db.Dictionarys.GetList("Dic_Key like '100%' and Dic_Key<>'100'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();
            if (selectID == 0)
            {
                selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择", Selected = true });
            }
            else
            {
                selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });
            }


            foreach (DictionaryModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData["selProductType"] = selectTypes;
        }

        public JsonResult GetProductsByType(int selectTypeId)
        {
            //加载产品类型
            List<ProductModel> dic_pro_types = new List<ProductModel>();
            if (selectTypeId == 0)
            {
                dic_pro_types = db.Products.GetList("");
            }
            else
            {
                dic_pro_types = db.Products.GetList("Dic_ProductType=" + selectTypeId);
            }
            return Json(new { data = dic_pro_types });
        }

        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="cardCode"></param>
        /// <param name="orderId"></param>
        /// <param name="productId"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public JsonResult AddToShoppingCart(string cardCode, int productId, int quantity)
        {
            ProductModel item = db.Products.GetModel(productId);
            Order_DetailsModel orderProduct = new Order_DetailsModel();
            orderProduct.Pro_ID = productId;
            orderProduct.ProductName = item.Name;
            orderProduct.Price = item.Price;
            orderProduct.Quantity = quantity;
            orderProduct.Image = item.Image;
            //查询当前会员卡的折扣
            VipCardModel curVip = curVip = GetDiscountByCardCode(cardCode);

            //根据是否会员用户启用不同折扣
            if (curVip != null)
            {
                orderProduct.Discount = curVip.Discount;  //会员折扣
                orderProduct.BuyPrice = item.Price * curVip.Discount;  //会员价
            }
            else
            {
                orderProduct.Discount = item.Discount;
                orderProduct.BuyPrice = item.Price * item.Discount;
            }


            //临时保存
            List<Order_DetailsModel> shoppingList = new List<Order_DetailsModel>();
            if (Session[KeysEnum.ShoppingCart.ToString()] != null)
            {
                shoppingList = (List<Order_DetailsModel>)Session[KeysEnum.ShoppingCart.ToString()];
                if (shoppingList.Exists(n => n.Pro_ID == productId))
                {
                    shoppingList.FirstOrDefault(n => n.Pro_ID == productId).Quantity += quantity;
                }
                else
                {
                    shoppingList.Add(orderProduct);
                }
            }
            else
            {
                shoppingList.Add(orderProduct);
            }
            Session[KeysEnum.ShoppingCart.ToString()] = shoppingList;

            decimal total = shoppingList.Sum(n => n.BuyPrice * n.Quantity);

            return Json(new { data = shoppingList, orderTotal = total });

        }

        public JsonResult Remove(int productId)
        {
            List<Order_DetailsModel> shoppingList = new List<Order_DetailsModel>();
            if (Session[KeysEnum.ShoppingCart.ToString()] != null)
            {
                shoppingList = (List<Order_DetailsModel>)Session[KeysEnum.ShoppingCart.ToString()];
                Order_DetailsModel item = shoppingList.FirstOrDefault(n => n.Pro_ID == productId);
                if (item != null)
                {
                    shoppingList.Remove(item);
                }
                Session[KeysEnum.ShoppingCart.ToString()] = shoppingList;
            }


            decimal total = shoppingList.Sum(n => n.BuyPrice * n.Quantity);

            return Json(new { data = shoppingList, orderTotal = total });
        }


        private VipCardModel GetDiscountByCardCode(string cardCode)
        {

            VipCardModel vipCard = db.VipCards.GetModel(cardCode);
            if (vipCard == null)
            {
                return null;
            }
            if (vipCard.Dic_CardType == ((int)CardTypeEnum.计次卡).ToString())
            {
                //次卡类型不处理
                return null;
            }

            DictionaryModel dic = db.Dictionarys.GetModel(vipCard.Dic_CardLevel);
            decimal discount = decimal.Parse(dic.Parameter);
            vipCard.Discount = discount;
            return vipCard;

        }

        public JsonResult GetCardInfo(string cardCode)
        {
            VipCardModel cardModel = GetDiscountByCardCode(cardCode);
            if (cardModel == null)
            {
                return Json(new { code = 1, msg = "卡号不存在！" });
            }
            List<WeChatUserModel> list = db.WeChatUsers.GetList(1, "VipCardCode='" + cardCode + "'", " AID DESC");
            if (list.Count > 0)
            {
                return Json(new { code = 2, user = list[0], card = cardModel });
            }
            else
            {
                return Json(new { code = 3, card = cardModel });
            }
        }

        [LogFilter("保存订单", OperateLogTypeEnum.订单日志, "cardCode")]
        public JsonResult SaveOrder(string cardCode)
        {
            //订单入库
            List<Order_DetailsModel> shoppingList = (List<Order_DetailsModel>)Session[KeysEnum.ShoppingCart.ToString()];
            string orderId = Tools.StringHelper.CreateNewOrderId(cardCode);
            OrderModel model = new OrderModel();
            //自动产生订单编号，用户ID 后3位
            model.Code = orderId;
            model.Buyer = cardCode;  //卡用户
            model.Creator = CurrentUser.UserName; //当前操作员
            model.CreateDate = DateTime.Now;
            model.LastUpdateDate = DateTime.Now;
            model.Payment = 0;
            model.PrePay = 0;

            // 查询当前卡用户的电话
            VipCardModel cardModel = db.VipCards.GetModel(cardCode);
            if (cardModel != null)
            {
                //区分次卡和储值卡.总价计算
                if (cardModel.Dic_CardType == ((int)CardTypeEnum.计次卡).ToString())
                {
                    model.Total = shoppingList.Sum(n => n.Quantity); //计次卡根据商品数量来消费
                    model.PayType = OrderPayTypeEnum.计次卡.ToString();
                }
                else if (cardModel.Dic_CardType == ((int)CardTypeEnum.储值卡).ToString())
                {
                    model.Total = shoppingList.Sum(n => n.BuyPrice * n.Quantity);  //储值卡根据价格来计费
                    model.PayType = OrderPayTypeEnum.储值卡.ToString();
                }

                //判断是否余额 够支付
                if (cardModel.Balance - model.Total < 0)
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "余额不足，保存失败!" });
                }

                model.Buyer_Phone = cardModel.Phone;
            }
            else
            {

                model.Buyer_Phone = "";
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在!" });
            }
            model.Buyer_Note = "";
            model.Buyer_Appointment = DateTime.Now;
            model.LastUpdateDate = DateTime.Now;
            model.Status = (int)OrderStateEnum.待支付; //已消费，待支付
            model.ComeFrom = OrderComeFrom.前台.ToString();

            //购买产品
            int rows = db.Orders.Add(model, shoppingList);
            if (rows > 0)
            {
                Session[KeysEnum.ShoppingCart.ToString()] = null;
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "保存成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "保存失败，请稍后重试！" });
            }
        }

        [LogFilter("发送验证码", OperateLogTypeEnum.订单日志, "orderId,cardCode,openid")]
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="openid">给当前用户发送验证码</param>
        /// <returns></returns>
        public JsonResult SendValidateCode(string orderId, string openid, string cardCode)
        {

            OrderModel odrModel = db.Orders.GetModel(orderId);

            //验证码入库
            string randCode = Tools.StringHelper.GetRandNumber();
            //一个用户只有一个验证码
            ValidateModel vldmodel = db.Validates.GetModel(openid);
            if (vldmodel == null)
            {
                vldmodel = new Core.Models.ValidateModel();
                vldmodel.Code = randCode;
                vldmodel.BizType = "PayCode"; //支付验证码
                vldmodel.BizId = odrModel.Code;
                vldmodel.OpenId = openid;
                vldmodel.StartDate = DateTime.Now;
                vldmodel.EndDate = vldmodel.StartDate.AddMinutes(5); //默认五分钟失效
                db.Validates.Add(vldmodel);
            }
            else
            {  //验证码存在，就刷新当前验证码
                vldmodel.Code = randCode;
                vldmodel.StartDate = DateTime.Now;
                vldmodel.EndDate = vldmodel.StartDate.AddMinutes(5); //默认五分钟失效
                db.Validates.Update(vldmodel);
            }

            string msg = string.Format("[美好时光]购买成功，订单{0},总计：{1}元。请回复验证码:[{2}], 5分钟内支付有效！", odrModel.Code, odrModel.Total, randCode);
            //发送微信手机号
            string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
            Senparc.Weixin.MP.Entities.WxJsonResult result = Senparc.Weixin.MP.AdvancedAPIs.Custom.SendText(access_token, openid, msg);
            if ((int)result.errcode == 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), data = vldmodel });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), data = vldmodel });
            }

        }

        [PermissionFilter]
        public ActionResult GoToPay(string Id)
        {
            ViewBag.OrderId = Id;
            return View();
        }

        /// <summary>
        /// 根据密码结算
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [PermissionFilter]
        public ActionResult Pay(string Id, string CardID)
        {
            VipCardModel model = db.VipCards.GetModel(CardID);
            if (model == null)
            {
                model = new VipCardModel();
            }

            ViewBag.OrderId = Id;
            return View(model);
        }

        public JsonResult GetOrder(string Id)
        {
            OrderModel model = db.Orders.GetModel(Id);
            return Json(new { data = model, orderTotal = model.Total });
        }
        /// <summary>
        /// 根据密码支付订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [LogFilter("完成支付", OperateLogTypeEnum.订单日志, "orderId")]
        public JsonResult PayOrder(string orderId, string pwd)
        {
            OrderModel model = db.Orders.GetModel(orderId);
            VipCardModel cardModel = db.VipCards.GetModel(model.Buyer);
            if (cardModel == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在" });
            }
            pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
            if (pwd != cardModel.Password)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "密码不正确" });
            }
            if (model.Status != (int)OrderStateEnum.待支付)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "订单状态必须为待支付" });
            }
            model.Payment = model.Total;
            model.Status = (int)OrderStateEnum.结单;
            model.LastUpdateDate = DateTime.Now;
            model.Creator = CurrentUser.UserName;
            int result = db.Orders.PayBill(model);
            if (result > 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "支付成功" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "支付失败，请稍后重试！" });
            }
        }

        /// <summary>
        /// 用户微信中回复验证码，自动完成订单支付
        /// </summary>
        /// <returns></returns>
        public JsonResult FinishOrder(string orderId)
        {
            OrderModel model = db.Orders.GetModel(orderId);
            if (model.Status == 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString() });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString() });
            }

        }


    }
}
